package com.scenic.userservice.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.Collect;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.CollectService;
import com.scenic.common.service.ScenicSpotService;
import com.scenic.userservice.mapper.CollectMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;
    @DubboReference
    private ScenicSpotService goodsService;
    @Override
    public boolean insert(Collect collect) throws ScenicSpotException {
        //查询收藏是否存在
        if (collectMapper.selectByGoodIdAndUserId(collect.getScenicSpotId(), collect.getUserId()) != null) {
            throw new ScenicSpotException("已经收藏该商品了，无法收藏");
        }

        return collectMapper.insert(collect) == 1;
    }

    @Override
    public boolean delete(Integer id, Integer userId) throws ScenicSpotException {
        //判断该收藏是否存在
        Collect collect = collectMapper.selectById(id);
        if (collect == null) {
            throw new ScenicSpotException("没有该收藏，无法删除");
        }
        //判断收藏是否是该用户的
        if (!collect.getUserId().equals(userId)) {
            throw new ScenicSpotException("不属于用户的收藏，，删除失败！");
        }
        return collectMapper.delete(id) == 1;
    }

    @Override
    public Collect selectByGoodIdAndUserId(Long goodsId, Integer userId) {
        return collectMapper.selectByGoodIdAndUserId(goodsId, userId);
    }

    @Override
    public PageInfo<Collect> selectByPage(Integer pageNum, Integer pageSize, Integer userId) throws ScenicSpotException {
        PageHelper.startPage(pageNum, pageSize);
        List<Collect> list = collectMapper.selectByUserId(userId);
        for (Collect collect : list) {
            collect.setScenicSpot(goodsService.selectById(collect.getScenicSpotId()));
        }
        PageInfo<Collect> PageInfo = new PageInfo<>(list);
        return PageInfo;
    }
}
